package cn.btks.commonserver.valid;

import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.math.BigDecimal;
import java.util.regex.Pattern;

/**
 * Created by zhangjing on 2019-4-3.
 * 该类用于重写前台传输的float、integer数据
 * 如果传输的数据非以上类型，设置为0或0。
 */
public class TypeConversionHandler {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Float.class, new FloatEditor());
        binder.registerCustomEditor(Integer.class, new IntegerEditor());
        binder.registerCustomEditor(BigDecimal.class, new BigDecimalEditor());
        binder.registerCustomEditor(Double.class, new DoubleEditor());
    }

    public class FloatEditor extends PropertiesEditor {

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if ("".equals(text)) {
                setValue("-9527.136");
            } else if (Pattern.compile("[0-9]*(\\.?)[0-9]*").matcher(text).matches()) {
                setValue(Float.parseFloat(text));
            } else {
                setValue("-9527.136");
            }
        }

        @Override
        public String getAsText() {
            return getValue().toString();
        }
    }

    public class IntegerEditor extends PropertiesEditor {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if (Pattern.compile("^[0-9]*$").matcher(text).find()) {
                setValue(Float.parseFloat(text));
            } else {
                setValue(0);
            }
        }

        @Override
        public String getAsText() {
            return getValue().toString();
        }
    }

    public class BigDecimalEditor extends PropertiesEditor {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if ("".equals(text)) {
                setValue("-9527.13");
            } else if (Pattern.compile("[0-9]*(\\.?)[0-9]*").matcher(text).matches()) {
                setValue(new BigDecimal(text));
            } else {
                setValue("-9527.13");
            }
        }

        @Override
        public String getAsText() {
            return getValue().toString();
        }
    }

    public class DoubleEditor extends PropertiesEditor {

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if ("".equals(text)) {
                setValue("-9527.138");
            } else if (Pattern.compile("[0-9]*(\\.?)[0-9]*").matcher(text).matches()) {
                setValue(Double.parseDouble(text));
            } else {
                setValue("-9527.138");
            }
        }

        @Override
        public String getAsText() {
            return getValue().toString();
        }
    }
}
